<script lang="ts" setup>
  import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
  import { ArrowLeftOutlined } from '@ant-design/icons-vue'
  import { message } from 'ant-design-vue'
  import { reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { requestSaveCompany, requestUpdateCompany } from '/@/api/business/company/org'
  import { requestGetCompanyById } from '/@/api/business/company/org'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  const token = getToken() || ''
  const router = useRouter()
  const route = useRoute()
  const isEdit = route.query.type === '1'
  const companyId = route.query.companyId || null
  const variable = reactive({
    confirmLoading: false,
    uploadLoading: false,
  })
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const formState: any = ref({
    companyName: '',
    socialUnifiedCode: '',
    companyContactName: '',
    companyContactPhone: '',
    companyAttachmentUrl: '',
    companyDesc: '',
    companyAccount: '',
    companyLabel: [],
  })
  const plainOptions = ['身份发行机构', '身份模拟机构', '应用机构', '积分发行', '存管银行', '监管机构'] //  0身份发行 1身份模板 2业务应用 3积分发行 4存管银行 5监管机构
  const formRef = ref()
  const fileList: any = ref([])
  const getCompanyById = async () => {
    const { responseCode, responseData } = await requestGetCompanyById({
      companyId: Number(companyId),
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      formState.value = { ...responseData }
      if (responseData?.companyAttachmentUrl) {
        fileList.value = [
          {
            name: responseData.companyAttachmentUrl.substring(responseData.companyAttachmentUrl.lastIndexOf('/') + 1),
            status: 'done',
            url: responseData.companyAttachmentUrl,
          },
        ]
      }
      formState.value.companyLabel = []
      const companyLabel = responseData.companyLabel.split(',')
      for (let i = 0; i < companyLabel.length; i++) {
        formState.value.companyLabel.push(plainOptions[companyLabel[i]])
      }
    }
  }
  isEdit && getCompanyById()
  const confirm = () => {
    formRef.value
      .validate()
      .then(async () => {
        variable.confirmLoading = true
        const api = !isEdit ? requestSaveCompany : requestUpdateCompany
        const companyLabel = formState.value.companyLabel.map((item) => {
          for (let i = 0; i < plainOptions.length; i++) {
            if (item === plainOptions[i]) {
              return i
            }
          }
        })
        const { responseCode } = await api({
          roleId: 1,
          companyId: route.query.companyId,
          companyName: formState.value.companyName,
          socialUnifiedCode: formState.value.socialUnifiedCode,
          companyContactName: formState.value.companyContactName,
          companyContactPhone: formState.value.companyContactPhone,
          companyAttachmentUrl: formState.value.companyAttachmentUrl,
          companyDesc: formState.value.companyDesc,
          companyAccount: formState.value.companyAccount,
          companyLabel: companyLabel.join(),
        }).finally(() => {
          variable.confirmLoading = false
        })

        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success(`${!isEdit ? '新建' : '更新'}机构成功`)
          router.back()
        }
      })
      .catch((res) => {
        console.log('catch: ', res)
      })
  }
  const onFinish = (values: any) => {
    console.log('Success:', values)
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  const rules = {
    companyName: {
      required: true,
      transform(value) {
        return value.trim()
      },
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, // 汉字、字母、数字
      validator: async (_, val) => {
        if (!val) {
          _.message = '请输入机构名称'
          return Promise.reject()
        }
        if (!_.pattern.test(val)) {
          _.message = '请输入正确的机构名称'
          return Promise.reject()
        }
        return Promise.resolve()
      },
    },
    socialUnifiedCode: {
      required: true,
      transform(value) {
        return value.trim()
      },
      pattern: /^[A-Za-z0-9]+$/,
      validator: async (_, val) => {
        if (!val) {
          _.message = '请输入统一社会信用编码'
          return Promise.reject()
        }
        if (!_.pattern.test(val)) {
          _.message = '请输入正确的统一社会信用编码'
          return Promise.reject()
        }
        return Promise.resolve()
      },
    }, // 数字、字母
    companyContactName: {
      required: true,
      transform(value) {
        return value.trim()
      },
      pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, // 汉字、字母
      validator: async (_, val) => {
        if (!val) {
          _.message = '请输入联系人'
          return Promise.reject()
        }
        if (!_.pattern.test(val)) {
          _.message = '请输入正确的联系人'
          return Promise.reject()
        }
        return Promise.resolve()
      },
    },
    companyContactPhone: {
      required: true,
      transform(value) {
        return value.trim()
      },
      pattern: /^((0\d{2,4}-\d{7,8})|(1[34578]\d{9}))$/,
      validator: async (_, val) => {
        if (!val) {
          _.message = '请输入联系人电话'
          return Promise.reject()
        }
        if (!_.pattern.test(val)) {
          _.message = '请输入正确的联系人电话'
          return Promise.reject()
        }
        return Promise.resolve()
      },
    }, // 手机和固话
    companyAccount: { required: true, message: '请输入数字资产钱包账号' },
    companyLabel: { required: true, message: '请选择机构标识' },
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      variable.uploadLoading = true
      return
    }
    if (info.file.status === 'done') {
      message.success('上传成功')
      formState.value.companyAttachmentUrl = info.file.response.responseData
      variable.uploadLoading = false
    }
    if (info.file.status === 'error') {
      variable.uploadLoading = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }

  const beforeUpload = (file) => {
    const isJpgOrPng = ['.rar', '.zip', '.doc', '.docx', '.pdf'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isJpgOrPng) {
      message.error('支持格式：.rar .zip .doc .docx .pdf')
    }
    const isLt2M = file.size / 1024 / 1024 < 50
    if (!isLt2M) {
      message.error('单个文件不能超过50M')
    }
    return isJpgOrPng && isLt2M
  }
</script>

<template>
  <div class="org-list-add">
    <div class="add-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="router.back()" />
      <span>{{ isEdit ? '编辑' : '新增' }}机构</span>
    </div>
    <a-divider />
    <div class="add-form-box">
      <div class="add-title">
        <span class="title">机构信息</span>
      </div>
      <a-form :model="formState" ref="formRef" name="form" :rules="rules" labelAlign="left" :wrapper-col="{ span: 20 }" autocomplete="off" @finish="onFinish" @finish-failed="onFinishFailed">
        <div class="flex">
          <a-form-item class="w-[50%]" label="机构名称" name="companyName">
            <a-input v-model:value="formState.companyName" placeholder="请输入机构名称" maxlength="60" />
          </a-form-item>
          <a-form-item class="w-[50%]" label="统一社会信用代码" name="socialUnifiedCode">
            <a-input v-model:value="formState.socialUnifiedCode" placeholder="请输入统一社会信用代码" maxlength="18" />
          </a-form-item>
        </div>
        <div class="flex">
          <a-form-item class="w-[50%]" label="联系人" name="companyContactName">
            <a-input v-model:value="formState.companyContactName" placeholder="请输入联系人" maxlength="40" />
          </a-form-item>
          <a-form-item class="w-[50%]" label="联系人电话" name="companyContactPhone">
            <a-input v-model:value="formState.companyContactPhone" placeholder="请输入联系人电话" maxlength="13" />
          </a-form-item>
        </div>
        <div class="flex">
          <a-form-item class="w-[50%]" name="companyAttachmentUrl" label="上传附件" extra="支持格式：.rar .zip .doc .docx .pdf 大小限制：单个文件不能超过50MB">
            <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUpload" @change="handleChange">
              <div>
                <loading-outlined v-if="variable.uploadLoading" :style="{ color: '#13c2c2' }" />
                <plus-outlined v-else :style="{ color: '#13c2c2' }" />
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item class="w-[50%]" label="机构简介" name="companyDesc">
            <a-textarea v-model:value="formState.companyDesc" :rows="4" placeholder="请输入" allow-clear />
          </a-form-item>
        </div>

        <div class="add-title">
          <span class="title">绑定管理员账号</span>
        </div>
        <div class="flex">
          <a-form-item class="w-[50%]" label="数字资产钱包账号" name="companyAccount">
            <a-input v-model:value="formState.companyAccount" placeholder="请输入数字资产钱包账号" />
          </a-form-item>
        </div>

        <div class="add-title">
          <span class="title">机构标识</span>
        </div>
        <a-form-item name="companyLabel" label="机构标识" :wrapper-col="{ span: 16 }">
          <a-checkbox-group v-model:value="formState.companyLabel" name="checkboxgroup" :options="plainOptions" />
        </a-form-item>
      </a-form>

      <div class="btn-wrap">
        <a-space>
          <a-button type="primary" html-type="submit" @click="confirm">确认</a-button>
          <a-button type="default" html-type="submit" @click="router.back()">取消</a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .org-list-add {
    background: #fff;
    padding-bottom: 32px;

    .add-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
      padding: 22px 0 0 26px;
    }

    .add-form-box {
      width: 80%;
      margin: 24px auto;

      .add-title {
        margin-bottom: 24px;
        clear: both;

        &::before {
          content: '';
          width: 3px;
          height: 13px;
          display: inline-block;
          background: #13c2c2;
          margin-right: 3px;
        }

        .title {
          font-size: 16px;
          font-weight: 500;
          color: #00474f;

          &::before {
            content: '';
            width: 2px;
            height: 10px;
            display: inline-block;
            background: #13c2c2;
            margin-right: 8px;
          }
        }
      }

      :deep(.ant-row) {
        display: unset;
        margin-bottom: 24px;
      }

      :deep(.ant-form-item) {
        margin-bottom: 0;
      }

      .flex {
        margin-bottom: 24px;
      }
    }

    .avatar-uploader > .ant-upload {
      width: 100px;
      height: 100px;
    }

    :deep(.ant-upload-select-picture-card) {
      border: 1px dashed #13c2c2;
      margin-bottom: 0;

      &:hover {
        border: 1px dashed #08979c;
      }
    }

    :deep(.ant-form-item-extra) {
      width: 220px;
      margin-top: 8px;
    }

    .ant-upload-select-picture-card .ant-upload-text {
      color: #41cdcd;
    }

    .btn-wrap {
      margin: 32px 0;
    }
  }
</style>
